package com.itheima.reggie.security;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * UsernamePasswordAuthenticationFilter是security的账号密码的校验器，只会拦截这个其他的请求不会拦截。
 */
@Slf4j
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
       // log.info("login:filter");
        //判断用户提交过来的用户名和密码 是否是使用的post请求 因为post请求是把数据放在请求体之中的
        try{
            Employee employee=null;
            if(!request.getMethod().equals("POST")){
                throw new AuthenticationServiceException("Authentication method not support"+request.getMethod());
            }else{
               employee = (Employee) JSON.parseObject(request.getInputStream(), Employee.class);
               log.info("employee:"+employee);
            }
            //将拦截下来的用户名和密码 封装到UsernamePasswordAuthenticationToken认证凭证，然后交给特定配置AuthenticationManager去认证。
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(employee.getUsername(), employee.getPassword());
            //身份认证管理器
           return  this.getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.attemptAuthentication(request, response);
    }

}
